import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { ArticleInfoEntity } from '../entity/info';
import { CoolCommException } from '@cool-midway/core';

/**
 * 文章信息
 */
@Provide()
export class ArticleInfoService extends BaseService {
  @InjectEntityModel(ArticleInfoEntity)
  articleInfoEntity: Repository<ArticleInfoEntity>;

  /**
   * 修改之前
   * @param data
   * @param type
   */
  async modifyBefore(data: any, type: 'delete' | 'update' | 'add') {
    if (type === 'update' && data.status === 1) {
      data.publishTime = new Date();
    }
  }

  /**
   * 删除文章分类
   * @param id
   */
  async deleteCategory(id: number) {
    const count = await this.articleInfoEntity.count({
      where: { categoryId: id },
    });
    if (count > 0) {
      throw new CoolCommException('该分类下存在文章，无法删除');
    }
  }

  /**
   * 查看帖子
   * @param id
   */
  async view(id: number) {
    await this.articleInfoEntity.increment({ id }, 'viewCount', 1);
  }

  /**
   * 点赞帖子
   * @param id
   */
  async like(id: number) {
    await this.articleInfoEntity.increment({ id }, 'likeCount', 1);
  }
}
